var target ;
var options = {
	success: function(data){
		$(target).empty().html(data).hide().fadeIn();			
		updateBreadCrumbs();		//Update the BreadCrumbs	
		notification("",false);		//关闭
	},
	error:  function(xhr, type, s){
		notification("",false);		//关闭
		alert("页面加载错误："+url);
	}
}


$(document).ready(function(){
	/**
	 *表单验证
	 *
	 *
	 */
	$('body').on('submit.form.data-api', '[data-toggle="form"]', function ( e ) {
		var formValue = $(e.target) ;
		notification("请稍候，正在加载······",true);	//开始
		formValue.ajaxSubmit({
			url:htmlsuf(formValue.attr("action")),
			success: function(data){
				if(formValue.attr("data-callback")){
					eval(formValue.attr("data-callback")+'($(formValue.attr("data-target")) , data)');
				}else{
					if(formValue.attr("data-target")){
						$(formValue.attr("data-target")).empty().html(data).hide().fadeIn();
					}
				}
				var action = formValue.attr("data-action") ;
				if(!action){
					$('#thisModal').modal('hide');
				}
				notification("",false);	//结束
			},
			error:function(xhr, type, s){
				$("#thisModal").empty().html(document.getElementById("myModal").innerHTML).hide().fadeIn();
				$("#thisModal").find("#modalbtn").on("click",function(){							
					$('#thisModal').modal('hide') ;
					$("#thisModal").empty();
				});
				if(xhr.getResponseHeader("emsg")){
					$("#msgbody").empty().html("<p>"+xhr.getResponseHeader("emsg")+"</p>");
					$('#thisModal').modal('show') ;
				}
				notification("",false);	//结束
			}
		});
		return false;
	});
	

	$('body').on('click.a.data-api', '[data-toggle="menu"]', function ( e ) {
		$(this).parent().find("[data-link]").removeClass("active");
		$(this).addClass("active");
		loadMainPage($(this).attr("data-link") , $(this).attr("data-target"));
	});
	$('body').on('click.a.data-api', function ( e ) {
		var toggle =  $(e.target).attr("data-toggle")?$(e.target).attr("data-toggle"):$(e.target).parents('[data-toggle="ajax"]').attr("data-toggle") ;
		if(toggle =="ajax"){
			return false;
		}
	});

	$('body').on('click.a.data-api', '[data-toggle="ajax"]', function ( e ) {
		loadMainPage($(this).attr("href") , $(this).attr("data-target"));
	});

	$('body').on('click.input.data-api','[data-toggle="checkbox"]', function ( e ) {
		var checked = $(e.target) ;
		checked.parent().parent().parent().next().find("tr>td:first-child>input:checkbox").each(function(){
			if(checked.attr("checked")){
				$(this).attr("checked",checked.attr("checked")) ;
			}else{
				$(this).attr("checked",false) ;
			}
		});
	});
	function resetModal(){
		$("#thisModal").empty().html('<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">    ×</button><h3 id="myModalLabel">    提示信息</h3></div><div class="modal-body"><p>    请稍候，正在加载页面</p>            </div>            <div class="modal-footer"><button class="btn btn-primary">    确定</button><button class="btn" data-dismiss="modal" aria-hidden="true">    取消</button></div>');
	}
	$('body').on('click', 'ul.menu>li', function ( e ) {
		$('ul.menu>li').each(function(){
			$(this).removeClass("active");
		});
		$(this).addClass("active");
	});

	function execDbClick(e , thisobj , url){
		$('#thisModal').modal('show') ;
		loadMainPage(url+thisobj.attr("data-id"), "#thisModal", null , function(xhr){
			if(xhr.getResponseHeader("emsg")){
				$("#thisModal").empty().html(document.getElementById("myModal").innerHTML).hide().fadeIn();
				$("#thisModal").find("#modalbtn").on("click",function(){
					$('#thisModal').modal('hide') ;
					$("#thisModal").empty();
				});
				if(xhr.getResponseHeader("emsg")){
					$("#msgbody").empty().html("<p>"+xhr.getResponseHeader("emsg")+"</p>");
				}
			}
		});
	}
	$('body').on('dblclick', '.newstitle', function ( e ) {
		execDbClick(e , $(this) , 'container/');
	});
	/**
	$('body').on('dblclick', '.designmodel', function ( e ) {
		execDbClick(e , $(this) , 'datamapping/');
	});
	**/
	/**  注册模式对话框事件处理 **/
	$('body').on('click.modal.data-api', '[data-toggle="modal"]', function ( e ) {
		var target = $(e.target).attr("data-target") ? $(e.target).attr("data-target") : $(e.target).parent().attr("data-target");
		if(target=='#thisModal'){
			resetModal();
			loadMainPage($(e.target).attr("href")?$(e.target).attr("href"):$(e.target).parent().attr("href") , target , null , function(xhr){
				if(xhr.getResponseHeader("emsg")){
					$("#thisModal").empty().html(document.getElementById("myModal").innerHTML).hide().fadeIn();
					$("#thisModal").find("#modalbtn").on("click",function(){
						$('#thisModal').modal('hide') ;
						$("#thisModal").empty();
					});
					if(xhr.getResponseHeader("emsg")){
						$("#msgbody").empty().html("<p>"+xhr.getResponseHeader("emsg")+"</p>");
					}
				}
			});
		}else if(target=='#myModal'){
			var action =  $(e.target).attr("data-action")? $(e.target).attr("data-action") : $(e.target).parent().attr("data-action");
			var actiontype =  $(e.target).attr("data-action-type")? $(e.target).attr("data-action-type") : $(e.target).parent().attr("data-action-type");
			if(actiontype && actiontype == "redirect"){
				loadMainPage(action, "#myModal>#msgbody", function(){
					$("#modaltitle").attr("data-href",$(e.target).attr("href")?$(e.target).attr("href") : $(e.target).parent().attr("href"));
					$("#modaltitle").attr("data-toggle","redirect");
				});	
			}else{
				loadMainPage(action ? action : "rmmodal", "#myModal>#msgbody" , function(){
					$("#modaltitle").empty();
					$("#modaltitle").attr("data-href",$(e.target).attr("href")?$(e.target).attr("href") : $(e.target).parent().attr("href"));
					if($(e.target).attr("data-callback")){
						$("#modaltitle").attr("data-callback",$(e.target).attr("data-callback"));
					}else{
						$("#modaltitle").removeAttr("data-callback");
					}
					$("#modaltitle").attr("data-target",$(e.target).attr("data-loadtarget")? $(e.target).attr("data-loadtarget") : "#workspace");
					$("#modaltitle").attr("data-toggle","ajax");
					var title = $(e.target).attr("title") ?  $(e.target).attr("title") : $(e.target).attr("data-title") ? $(e.target).attr("data-title") : $(e.target).parent().attr("data-title") ? $(e.target).parent().attr("data-title") : $(e.target).parent().attr("title") ;
					$("#modaltitle").html(title ? title : $(e.target).parent().prev().children().first().children().first().attr("title"));
				});					
			}
		}
	}) ;
	$('#modalbtn').on('click', function () {
		if(document.getElementById("modaltitle")){
			var href = $("#modaltitle").attr("data-href") ;
			var toggle = $("#modaltitle").attr("data-toggle") ;
			var target =  $("#modaltitle").attr("data-target") ;
			var callback = $("#modaltitle").attr("data-callback") ;
			if(toggle && toggle=="redirect"){
				window.location.href = href ;
			}else{
				if(href && href!=''){
					loadURL(htmlsuf(href) , target =="r3_command" ? null : target , function(data){
						$('#myModal').modal('hide') ;
						if(callback){
							eval(callback);
						}
					} , function(xhr){						
						if(xhr.getResponseHeader("emsg")){
							$("#msgbody").empty().html("<p>"+xhr.getResponseHeader("emsg")+"</p>");
						}
						if(!$('#myModal').is(":hidden")){
							$('#myModal').modal('show') ;
						}
					});
				}
			}
		}else{
			$('#myModal').modal('hide') ;
		}		
	});
	$('body').on('click.modal.data-api', '[data-dismiss="modal"]', function ( e ) {
		$('#myModal').modal('hide') ;
		$('#thisModal').modal('hide') ;
	});


	$('#myModal').on('hidden', function () {
		if($("#modaltitle")){
			$("#modaltitle").empty();
			$("#modaltitle").attr("data-href","");
		}
		$(this).unbind();
	});
	$('#thisModal').on('hidden', function () {
		$(this).unbind();
	});
});



//Update Sidebar Active tab using this function
function updateSidebar(item){
	var target = $(".sideBar>ul>li[data-link='"+item+"']>figure:first-child")[0];
	//console.log(item,target);
	var ac = $('.sideBar > ul >li.active')[0];
	$(target).parent().addClass('active');
	$(ac).removeClass('active');
}


//This function is responsible for ajax loading of pages and the default actions that run everytime a new page is loaded
function loadPage(page){
	loadURL(htmlsuf(page.toString()),".content");
	updateSidebar(page);
}

//This function is responsible for ajax loading of pages and the default actions that run everytime a new page is loaded
function loadMainPage(page , panel , callback , errorcallback , tinfo,recall){
	loadURL(htmlsuf(page.toString()) , panel ,callback , errorcallback , tinfo,recall);
}

//This function is responsible for ajax loading of pages and the default actions that run everytime a new page is loaded
function loadURL(url){
	loadURL(url , '.workspace');
}
//This function is responsible for ajax loading of pages and the default actions that run everytime a new page is loaded
function loadURL(url , panel , callback , errorcallback , tinfo ,recall){
	if(tinfo){}else{
		notification("请稍候，正在加载······",true);	//开始
	}	
	$.ajax({
		url:url,
		cache:false,
		success: function(data){
			if(panel){
				$(panel).empty().html(data).hide().fadeIn();
			}			
			if(tinfo){}else{
				notification("",false);		//关闭
			}
			if(callback && typeof callback == 'function') {
				callback();
			} else if(callback) {
				eval(callback);
			}
			//if(callback){
			//	callback(data);
			//}
			$(".ui-wrapper").css("padding-right","0px");
			$(".ui-wrapper").css("padding-bottom","0px");
			$("#tempdiv").empty();			
		},
		error:  function(xhr, type, s){			
			if(tinfo){				
				
			}else{
				notification("",false);		//关闭
			}
			if(errorcallback && typeof errorcallback == 'function') {
				errorcallback();
			} else if(errorcallback) {
				eval(errorcallback);
			}
			//if(errorcallback){
			//	errorcallback(xhr);
			//}
		}
	}).done(function(){
		if(recall && typeof recall == 'function') {
			recall();
		} else if(recall) {
			eval(recall);
		}
	});
}
function html(panel, data){
	$(panel).empty().html(data).hide().fadeIn();
	$( "#designdiv").sortable({
			handle:".sorthandler",
			revert: true , 
			connectWith:"#designdiv"  , 
			stop:function(event, ui){
				saveDesign();
			}, 
			items:".sortrow:not(.ui-state-disabled)",
			cancel: ".ui-state-disabled"
		}).disableSelection();	
	registerEvent();
	/**
	$( "#designdiv").selectable({
		stop: function() {
			//$(this).addClass("ui-state-disabled");
		}
	});
	**/
}
function getText(url , data){
	var text ;
	$.ajax({  
		async:false,//使用同步的Ajax请求  
		type: "GET",  
		url: htmlsuf(url),  
		data: data,  
		success: function(msg){  
			text=msg;  
		}  
	}); 
	return text ;
}
function loadSubPage(page){
	$.ajax({
		url:page.toString()+'.html',
		cache:false,
		success: function(data){
			$('.workspace').empty();
			$('.workspace').html(data);
		}
	}).done(function(){
		
	});
}

function htmlsuf(href){
	return href.indexOf('.html')>0 ? href : href+".html" ;
}

function fixLayout(){
	
}

function notify(_msg,_type,_time){
	window.setTimeout(function(){
		$('.notification').remove();
		var p = $("<p/>").text(_msg).addClass('notification stripe stripeS activeS').addClass(_type);
		$('header').append(p);
		var wid = parseInt($('body').width()/2-$(p)[0].offsetWidth/2);
		$(p).css('left',wid.toString()+'px');
		$(p).hide().fadeIn();
	},_time);
}





function updateBreadCrumbs(){
	$('.bcrumbs li:last-child').text($('.sideBar ul li.active figure').text());
}


var ninja = document.createElement('div');
$(ninja).on("tablesLoaded",function(){
	$('table').tablesorter();
});


function updateAutoComplete(_source){
	$('#searchInput').typeahead({
		source: _source,
		items: 8
	});
}

function trToArray(_tbodyelement){
	var jso=[];
	$(_tbodyelement).find('tr').each(function(index){ 
		jso.push($(this).find('td')[0].textContent);
	});
	return jso;
}



/*---------------------------------------------------------------------------------------------------
------------------------------  NOTIFICATIONS MODULE ------------------------------------------------
--------------- TUSHAR KANT SAHAY Copyright 2012 , nanu.clickity@gmail.com --------------------------
---------------------------------------------------------------------------------------------------*/

function notification(_message, _notificationType, _timeOut){
	$('.notification').remove();
	var p = $("<p/>").text("请稍候，正在加载······").addClass('notification stripe stripeS activeS').addClass(_notificationType);
	$('header').append(p);
	var wid = parseInt($(document).width()/2-$(p)[0].offsetWidth/2);
	$(p).css('left',wid.toString()+'px');
	$(p).css('top',$(document).height()*1/3+'px');
	$(p).hide().fadeIn();
	window.setTimeout( function(){
		$('.notification').fadeOut();
	},parseInt(_timeOut));
}

/*---------------------------------------------------------------------------------------------------
------------------------------  NOTIFICATIONS MODULE ------------------------------------------------
--------------- TUSHAR KANT SAHAY Copyright 2012 , nanu.clickity@gmail.com --------------------------
---------------------------------------------------------------------------------------------------*/

function notification(_message , type){
	if(type){
		$('.notification').remove();
		var p = $("<p/>").text("请稍候，正在加载······").addClass('notification stripe stripeS activeS').addClass("blue");
		$('header').append(p);
		var wid = parseInt($(document).width()/2-$(p)[0].offsetWidth/2);
		$(p).css('left',wid.toString()+'px');
		$(p).css('top',$(document).height()*1/3+'px');
		$(p).hide().fadeIn();
	}else{
		$('.notification').fadeOut();
	}
}


/**
 * jQuery alterClass plugin
 *
 * Remove element classes with wildcard matching. Optionally add classes:
 *   $( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' )
 *
 * Copyright (c) 2011 Pete Boere (the-echoplex.net)
 * Free under terms of the MIT license: http://www.opensource.org/licenses/mit-license.php
 *
 */
(function ( $ ) {
	
$.fn.alterClass = function ( removals, additions ) {
	
	var self = this;
	
	if ( removals.indexOf( '*' ) === -1 ) {
		// Use native jQuery methods if there is no wildcard matching
		self.removeClass( removals );
		return !additions ? self : self.addClass( additions );
	}
 
	var patt = new RegExp( '\\s' + 
			removals.
				replace( /\*/g, '[A-Za-z0-9-_]+' ).
				split( ' ' ).
				join( '\\s|\\s' ) + 
			'\\s', 'g' );
 
	self.each( function ( i, it ) {
		var cn = ' ' + it.className + ' ';
		while ( patt.test( cn ) ) {
			cn = cn.replace( patt, ' ' );
		}
		it.className = $.trim( cn );
	});
 
	return !additions ? self : self.addClass( additions );
};
 
})( jQuery );